import { exec } from 'child_process'
import { promisify } from 'util'
import * as os from 'os'

const execAsync = promisify(exec)

export interface SystemIdentifiers {
  systemUuid: string
  systemSerial: string
  osSerial: string
  hostname: string
  fqdn: string
}

/**
 * 获取系统唯一标识符 - 优化版本，使用原生API和快速命令
 * @returns Promise<SystemIdentifiers> 系统唯一标识符对象
 */
export async function getSystemIdentifiers(): Promise<SystemIdentifiers> {
  try {
    const platform = process.platform
    let systemUuid = ''
    let systemSerial = ''
    let osSerial = ''

    if (platform === 'win32') {
      // Windows - 使用快速的WMI查询
      const [uuidResult, serialResult, osSerialResult] = await Promise.all([
        execAsync('wmic csproduct get UUID /value'),
        execAsync('wmic bios get serialnumber /value'),
        execAsync('wmic os get serialnumber /value')
      ])
      
      systemUuid = extractValue(uuidResult.stdout, 'UUID')
      systemSerial = extractValue(serialResult.stdout, 'SerialNumber')
      osSerial = extractValue(osSerialResult.stdout, 'SerialNumber')
    } else if (platform === 'darwin') {
      // macOS - 使用系统命令
      const [uuidResult, serialResult] = await Promise.all([
        execAsync('system_profiler SPHardwareDataType | grep "Hardware UUID"'),
        execAsync('system_profiler SPHardwareDataType | grep "Serial Number"')
      ])
      
      systemUuid = extractValue(uuidResult.stdout, 'Hardware UUID')
      systemSerial = extractValue(serialResult.stdout, 'Serial Number')
      osSerial = systemSerial // macOS通常使用相同的序列号
    } else {
      // Linux - 使用系统文件
      const [uuidResult, serialResult] = await Promise.all([
        execAsync('cat /sys/class/dmi/id/product_uuid 2>/dev/null || echo "unknown"'),
        execAsync('cat /sys/class/dmi/id/product_serial 2>/dev/null || echo "unknown"')
      ])
      
      systemUuid = uuidResult.stdout.trim()
      systemSerial = serialResult.stdout.trim()
      osSerial = systemSerial
    }

    // 获取主机名和FQDN（这些很快）
    const hostname = os.hostname()
    const fqdn = hostname // 简化处理，实际项目中可能需要DNS查询

    return {
      systemUuid: systemUuid || 'unknown',
      systemSerial: systemSerial || 'unknown',
      osSerial: osSerial || 'unknown',
      hostname: hostname || 'unknown',
      fqdn: fqdn || 'unknown'
    }
  } catch (error) {
    console.error('获取系统唯一标识符失败:', error)
    // 返回默认值而不是抛出错误
    return {
      systemUuid: 'unknown',
      systemSerial: 'unknown',
      osSerial: 'unknown',
      hostname: os.hostname() || 'unknown',
      fqdn: os.hostname() || 'unknown'
    }
  }
}

/**
 * 从命令输出中提取值
 */
function extractValue(output: string, key: string): string {
  const lines = output.split('\n')
  for (const line of lines) {
    if (line.includes(key)) {
      const parts = line.split('=')
      if (parts.length > 1) {
        return parts[1].trim()
      }
      // 处理macOS格式
      const colonIndex = line.indexOf(':')
      if (colonIndex > -1) {
        return line.substring(colonIndex + 1).trim()
      }
    }
  }
  return 'unknown'
}
